package com.cssw.fyzb.event.config;

import com.cssw.fyzb.core.model.dodb._MappingKit;
import com.ydn.dbframe.plugin.activerecord.ActiveRecordPlugin;
import com.ydn.dbframe.plugin.activerecord.DruidPlugin;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author Feng Chen
 */
@Setter
@Getter
@Component
public class DbConfig {

    private static final String DATASOURCE = "fyzb";

    @Value("${mysql.url}")
    private String url;

    @Value("${mysql.username}")
    private String username;

    @Value("${mysql.password}")
    private String password;

    @Value("${mysql.minIdle:3}")
    private int minIdle;

    @Value("${mysql.maxActive:5}")
    private int maxActive;

    private DruidPlugin druidPlugin;
    private ActiveRecordPlugin activeRecordPlugin;

    private static final Logger logger = LoggerFactory.getLogger(DbConfig.class);

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;

    }

    /**
     * 启动服务
     */
    @PostConstruct
    public void start() {
        logger.info("db start...");
        druidPlugin = new DruidPlugin(url, username, password);
        druidPlugin.setMinIdle(minIdle);
        druidPlugin.setMaxActive(maxActive);
        activeRecordPlugin = new ActiveRecordPlugin(DATASOURCE, druidPlugin);
        _MappingKit.mapping(activeRecordPlugin);
        druidPlugin.start();
        activeRecordPlugin.start();
    }

    /**
     * 关闭服务
     */
    @PreDestroy
    public void close() {
        logger.info("db close...");
        activeRecordPlugin.stop();
        druidPlugin.stop();
    }

}
